#!/usr/bin/env bash
# This script is necessary on nix environment because not LHS (Linux Hierarchy Standard), so no
# dynamic link available
# This script patch libs *.so* from python packages to add others libs on ld_libs rpath.
# Also override system default library locations by nix packages (described on flake.nix devShell).
#
verbose=false
case $1 in
  -v|--verbose|-d|--debug)
    verbose=true
    ;;
esac

VENV=$(poetry env info --path)
[ -z "$VENV" ] && poetry install
VENV=$(poetry env info --path)
libs=$(find $VENV -name '*.so*')
LD_LIBS=$LD_LIBRARY_PATH_BASE:$(echo $libs |xargs dirname | sort -u | tr '\n' ':')
LD_LIBS=${LD_LIBS%:}
[ "$VENV" ] || { echo "No venv found" >&2; exit 1; }

for i in $libs
do
  [ "${i%.orig}" != "$i" ] && continue
  [ -f $i.orig ] || cp $i $i.orig
  if $verbose; then
    echo "*** Patching $i ***"
    echo before:
    ldd $i
  fi
  patchelf --set-rpath $LD_LIBS $i
  if $verbose; then
    echo after:
    ldd $i
  fi
done
